package wxapp

import (
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"hotgo/internal/dao"
	"hotgo/internal/library/hgorm"
	"hotgo/internal/model/input/apiin"
	"hotgo/internal/model/input/sysin"
)

// SinglePage 单页
func (s *sWxapp) SinglePage(ctx context.Context, id int) (title string, content string, err error) {
	res, err := dao.AdminNotice.Ctx(ctx).Where(g.Map{"id": id}).One()
	if err != nil {
		return
	}
	if res.IsEmpty() {
		err = gerror.New("id不存在")
		return
	}
	title = gconv.String(res["title"])
	content = gconv.String(res["content"])
	return
}

// OrderList 订单列表
func (s *sWxapp) OrderList(ctx context.Context, page int, pageSize int, status int) (*[]apiin.OrderList, int, error) {

	openid := ctx.Value("openid").(string)
	list := make([]apiin.OrderList, 0)
	totalCount := 0
	mod := dao.VideoOrder.Ctx(ctx)

	// 字段过滤
	mod = mod.FieldsPrefix(dao.VideoOrder.Table(), sysin.VideoOrderListModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.VideoOrderListModel{}, &dao.Activity, "activity"))
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.VideoOrderListModel{}, &dao.UserVideo, "userVideo"))

	// 关联表字段
	mod = mod.LeftJoinOnFields(dao.Activity.Table(), dao.VideoOrder.Columns().ActivityId, "=", dao.Activity.Columns().Id)
	mod = mod.LeftJoinOnFields(dao.UserVideo.Table(), dao.VideoOrder.Columns().VideoId, "=", dao.UserVideo.Columns().Id)

	// 查询openid
	mod = mod.WhereLike(dao.VideoOrder.Columns().OpenId, openid)

	// 查询状态
	if status != 2 {
		mod = mod.Where(dao.VideoOrder.Columns().Status, status)
	}
	all, err := mod.All()
	if err != nil {
		return &list, totalCount, nil
	}
	totalCount = len(all)
	// 分页
	mod = mod.Page(page, pageSize)

	// 排序
	mod = mod.OrderDesc(dao.VideoOrder.Table() + "." + dao.VideoOrder.Columns().Id)

	// 查询数据
	res, err := mod.All()
	if err != nil {
		return &list, totalCount, nil
	}
	for _, v := range res {
		order := apiin.OrderList{}
		order.Id = gconv.Int(v["id"])
		order.Title = gconv.String(v["activityTitle"])
		order.CoverImg = gconv.String(v["activityCoverImg"])
		order.Price = gconv.Float64(v["price"])
		order.VideoUrl = gconv.String(v["userVideoVideoUrl"])
		order.Path = gconv.String(v["userVideoPath"])
		order.Status = gconv.Int(v["status"])
		order.PayTime = gconv.String(v["update_at"])
		list = append(list, order)
	}
	/*if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取订单管理列表失败，请稍后重试！")
		return
	}*/
	return &list, totalCount, nil
}
